package com.douwong.student.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.douwong.student.R;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.base.ClassBaseActivity;
import com.douwong.student.contant.CommonConfig;
import com.douwong.student.contant.Config;
import com.douwong.student.enums.E_CommandType;
import com.douwong.student.enums.E_Destination;
import com.douwong.student.factory.ThreadFactory;
import com.douwong.student.interfaces.ColorChangedListener;
import com.douwong.student.model.AnswerRecord;
import com.douwong.student.popuwindow.ColorPickerPopuwindow;
import com.douwong.student.popuwindow.UpLoadPopuWindow;
import com.douwong.student.socket.LTPServer;
import com.douwong.student.utils.CommonPlaneCommit;
import com.douwong.student.utils.DensityUtil;
import com.douwong.student.utils.FileUtils;
import com.douwong.student.utils.FtpUtils;
import com.douwong.student.utils.ImageUtils;
import com.douwong.student.utils.LogUtils;
import com.douwong.student.utils.ScreenUtils;
import com.douwong.student.utils.ToastUtils;
import com.douwong.student.utils.UIUtils;
import com.douwong.student.view.PaletteView;
import com.douwong.student.view.ScaleImageView;
import com.lidroid.xutils.bitmap.core.BitmapDecoder;
import com.lidroid.xutils.bitmap.core.BitmapSize;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import static com.douwong.student.R.id.draw_img;
import static com.douwong.student.R.id.tool_ll;


/**
 * @autor yichao
 * @time 2017/5/1716:45
 * @des 课堂全班作答
 */

public class HandWriteAllClassAnswerActivity extends ClassBaseActivity {
    private static final String TAG = "RadomAnswerActivity";
    private PaletteView mPaintView;
    private UpLoadPopuWindow mUpLoadPopu;
    private LinearLayout mTool_ll,mUpload_ll,mClear_ll,mPen_ll,mLast_ll,mNext_ll,mEaser_ll,mDown_ll;
    private TextView mName,mProgress_text;
    private ScaleImageView mDraw_img;
    private ImageView mLoad_img,mCommit_img,mPlane_img,mScale_img;
    private int mLastColor,mLastSize;
    private ColorPickerPopuwindow mPopu;
    private final int FTP_DOWN_LOADING = 220;
    private final int FTP_DOWN_SUCCESS = 221;
    private final int FTP_DOWN_FAIL = 222;
    private final int FTP_UPLOAD_LOADING = 320;
    private final int FTP_UPLOAD_SUCCESS = 321;
    private final int FTP_UPLOAD_FAIL = 322;
    private CommonPlaneCommit mCommonPlaneCommit;
    private int mDeviceWidth;
    private int mDeviceHeight;
    private Bitmap mBitmap;
    private boolean hasCommit=false;//是否提交答案
    private String mFilePath;
    private AnswerRecord mAnswerRecord;
    private Bitmap mTempBitmap;
    private String mImageName;
    private String mFtpDir;

    public static void startActivity(Context context,String data){
        Intent intent=new Intent(context,HandWriteAllClassAnswerActivity.class);
        intent.putExtra(Config.INTENT_DATA,data);
        context.startActivity(intent);
    }

    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case FTP_DOWN_LOADING:
                    long proess = (long) msg.obj;
                    mProgress_text.setText(proess + "%");

                    break;
                case FTP_DOWN_SUCCESS:
                    mUpload_ll.setVisibility(View.INVISIBLE);
                    mUpLoadPopu.dismiss();
                 //   mRlRootView.setVisibility(View.VISIBLE);
                   /* File    mFile = (File) msg.obj;
                    BitmapFactory.Options opts = new BitmapFactory.Options();
                    opts.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(mFile.getAbsolutePath(), opts);
                    opts.inPreferredConfig = Bitmap.Config.ARGB_4444;
                    opts.inSampleSize = calculateInSampleSize(opts, mDeviceWidth, mDeviceHeight);
                    opts.inJustDecodeBounds = false;
                    mBitmap = BitmapFactory.decodeFile(mFile.getAbsolutePath(), opts);
                    mDraw_img.setDispResource(mBitmap,mDeviceWidth, mDeviceHeight);*/
                    File    mFile = (File) msg.obj;
                    mBitmap=   handleImage(mFile.getAbsolutePath());
                    mDraw_img.setDispResource(mBitmap,mDeviceWidth, mDeviceHeight);
                    break;
                case FTP_DOWN_FAIL:
                 //   mLlUpdata.setVisibility(View.INVISIBLE);
                    finish();
                    ToastUtils.makeText(HandWriteAllClassAnswerActivity.this,"图片下载失败");
                    break;

                case FTP_UPLOAD_LOADING:
                 int currentSize= (int) msg.obj;
                    mUpLoadPopu.setProgress(currentSize);
                    break;
                case FTP_UPLOAD_SUCCESS:
                    mUpLoadPopu.setProgress(100);
                    mUpLoadPopu.dismiss();
                    mCommit_img.setSelected(true);
                    mCommit_img.setFocusable(false);
                    hasCommit=true;
                    mTool_ll.setVisibility(View.INVISIBLE);
                    mPaintView.isDraw = false;
                    mDraw_img.isDrag =false;
                    LTPServer.createInstance(HandWriteAllClassAnswerActivity.this).sendMsg(mFtpDir+mImageName,
                            E_CommandType.answerClass,
                            E_Destination.teacher,new int[]{BaseApplication.sTeacherOnline.teacher.teacherId});
                    //关闭activity
                    finish();
                    break;
                case FTP_UPLOAD_FAIL:
                    hasCommit=false;
                    mTool_ll.setVisibility(View.VISIBLE);
                    mCommit_img.setSelected(false);
                    mCommit_img.setFocusable(true);
                    finish();
                    break;
            }
        }
    };
    /**
     * 文件路径装化Bitmap
     * @param path
     * @return
     */
    private Bitmap handleImage(String path) {
        BitmapSize maxSize = new BitmapSize((int) (mDeviceWidth * CommonConfig.ReciveImgZoomProportion),
                (int) (mDeviceHeight * CommonConfig.ReciveImgZoomProportion));
        return BitmapDecoder.decodeSampledBitmapFromFile(path, maxSize, Bitmap.Config.RGB_565);
    }

    IntentFilter mFilter=new IntentFilter(){
            {
            addAction(Config.TEACHER_LEAVE_CLASS);
            addAction(Config.LOGIN_CLASS_FAILURE);
        }
    };
    BroadcastReceiver mReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case Config.LOGIN_CLASS_FAILURE:
                case Config.TEACHER_LEAVE_CLASS:
                    logcatI(intent.getAction());
                    finish();
                    break;
            }

        }
    };
    @Override
    protected void initView() {
        setContentView(R.layout.handwritten_layout);
        mCommit_img = (ImageView) findViewById(R.id.commit);
        mPaintView = (PaletteView) findViewById(R.id.paintview);
        mTool_ll = (LinearLayout) findViewById(tool_ll);
        mUpload_ll = (LinearLayout) findViewById(R.id.upload_ll);

        mClear_ll = (LinearLayout) findViewById(R.id.clear_ll);
        mPen_ll = (LinearLayout) findViewById(R.id.pen_ll);
        mLast_ll = (LinearLayout) findViewById(R.id.last_ll);
        mNext_ll = (LinearLayout) findViewById(R.id.next_ll);
        mEaser_ll = (LinearLayout) findViewById(R.id.easer_ll);
        mScale_img = (ImageView) findViewById(R.id.scale_img);
        mName = (TextView) findViewById(R.id.name);

        mDraw_img = (ScaleImageView) findViewById(draw_img);
        mPlane_img = (ImageView) findViewById(R.id.plane_img);
        mDown_ll = (LinearLayout) findViewById(R.id.down_ll);
        mProgress_text = (TextView) findViewById(R.id.progress_text);

        mLoad_img = (ImageView) findViewById(R.id.load_img);

    }
    @Override
    protected void initData() {
        super.initData();
        registerReceiver(mReceiver,mFilter);
        mPopu = new ColorPickerPopuwindow(HandWriteAllClassAnswerActivity.this);
        mPaintView.setPopuwindow(mPopu);
        mUpLoadPopu = new UpLoadPopuWindow(HandWriteAllClassAnswerActivity.this);

        mLastColor = getResources().getColor(R.color.color_11);
        mLastSize = 5;
        mPaintView.isDraw = false;
        mTool_ll.setVisibility(View.INVISIBLE);
        doPencil(mPaintView);

        mDeviceWidth = ScreenUtils.getScreenWidth();
        mDeviceHeight = ScreenUtils.getScreenHeight();
        mCommonPlaneCommit = new CommonPlaneCommit(this, mPlane_img, mDeviceWidth, mDeviceHeight);


        mTool_ll.setVisibility(View.VISIBLE);
        mCommit_img.setVisibility(View.VISIBLE);

        //获取下载地址
        Intent intent=getIntent();
         String imageFtpUrl=  intent.getStringExtra(Config.INTENT_DATA);
        if (imageFtpUrl!=null){
           downFilePic(imageFtpUrl);


        }else {
            ToastUtils.makeText(this,"文件地址错误");
            finish();
        }
        mAnswerRecord = new AnswerRecord();
      /*  mTool_ll.setVisibility(View.VISIBLE);
        mCommit_img.setVisibility(View.VISIBLE);*/

    }

    /**
     * 下载图片
     *
     * @param imageUrl
     */
    private void downFilePic(final String imageUrl) {
        ThreadFactory.getDownLoadPool().execute(new Runnable() {
            @Override
            public void run() {
                int index = imageUrl.lastIndexOf("/");
                mImageName = imageUrl.substring(index + 1, imageUrl.length());
                FtpUtils ftp = new FtpUtils();
                try {

                    ftp.downloadSingleFile(imageUrl, FileUtils.IMAGE_DIR, mImageName, new FtpUtils.DownLoadProgressListener() {
                        @Override
                        public void onDownLoadProgress(String currentStep, long downProcess, File file) {
                            Message message = mHandler.obtainMessage();
                            logcatI("当前 下载手写互动图片 ："+currentStep);
                            switch (currentStep) {
                                case Config.FTP_DOWN_FAIL:
                                    ToastUtils.makeText(UIUtils.getContext(), "手写互动下载图片失败");
                                    message.what = FTP_DOWN_FAIL;
                                    mHandler.sendMessage(message);

                                    break;
                                case Config.FTP_DOWN_LOADING:
                                    message.what = FTP_DOWN_LOADING;
                                    LogUtils.i(TAG, "下载进度" + downProcess);
                                    message.obj = downProcess;
                                    mHandler.sendMessage(message);
                                    break;
                                case Config.FTP_DOWN_SUCCESS:
                                    message.what = FTP_DOWN_SUCCESS;
                                    message.obj = file;
                                    mHandler.sendMessage(message);
                                    break;
                                case Config.FTP_CONNECT_FAIL:
                                case Config.FTP_FILE_NOTEXISTS:
                                    ToastUtils.makeText(HandWriteAllClassAnswerActivity.this,currentStep);
                                    finish();
                                    break;

                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    finish();
                    ToastUtils.makeText(HandWriteAllClassAnswerActivity.this, "随机作答下载图片失败");
                }
            }
        });

    }

    @Override
    protected void initEvent() {
        super.initEvent();

        HandWrittenOnClick listener = new HandWrittenOnClick();

        mScale_img.setOnClickListener(listener);
        mClear_ll.setOnClickListener(listener);
        mPen_ll.setOnClickListener(listener);
        mLast_ll.setOnClickListener(listener);
        mNext_ll.setOnClickListener(listener);
        mDown_ll.setOnClickListener(listener);
        mEaser_ll.setOnClickListener(listener);
        mCommit_img.setOnClickListener(listener);
        mUpload_ll.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mUpload_ll.setVisibility(View.INVISIBLE);
            }
        });

    }
    public void doPencil( PaletteView paletteView) {
        paletteView.setColor(mLastColor);
        paletteView.setSize(mLastSize);
    }
    private ColorChangedListener colorChange = new ColorChangedListener() {

        @Override
        public void sizeChanged(int size) {
            mLastSize = size;
            mPaintView.setSize(mLastSize);
        }

        @Override
        public void colorChanged(int color) {
            mLastColor = color;
            mPaintView.setColor(mLastColor);
        }
    };

    private class HandWrittenOnClick implements View.OnClickListener {

        @Override
        public void onClick(View v) {

            if (mPopu!=null&&mPopu.isShowing() && v.getId() != R.id.pen_ll) {
                mPopu.dismiss();
            }
            switch (v.getId()) {
                //			 橡皮擦
                case R.id.easer_ll:
                   mPaintView.isDraw=true;
                    mDraw_img.isDrag = false;
                    mPaintView.changePenMode(2);
                    break;
                case R.id.scale_img:
                    mPaintView.isDraw = false;

                    mDraw_img.isDrag = true;
                    break;
                case R.id.clear_ll:
                    mPaintView.clear();

                    break;
                case R.id.pen_ll:

                    mDraw_img.isDrag = false;
                    mPaintView.isDraw = true;

                    int[] location = new int[2];
                    v.getLocationOnScreen(location);
                    int x = (int) (location[0] - DensityUtil.dip2px(HandWriteAllClassAnswerActivity.this, 500)
                            - v.getWidth() * 1.3);


                    if (!mPopu.isShowing()) {
                        mPopu.showAtLocation(v, Gravity.NO_GRAVITY, x, location[1]);
                        mPopu.setOnColorChangerLister(colorChange);
                        mPopu.setOnDismissListener(new PopupWindow.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                                mPaintView.changePenMode(1);
                            }
                        });
                    } else {
                        mPopu.dismiss();
                    }
                    break;

                // 上一步
                case R.id.last_ll:
                    mPaintView.undo(-1);
                    //				paintView.goBackOnce();
                    break;
                // 下一步
                case R.id.next_ll:
                    mPaintView.undo(1);
                    //				paintView.next();
                    break;
                // 重新下载图片
                case R.id.down_ll:

                    break;
                // 提交图片
                case R.id.commit:
                    if (!BaseApplication.isLoginClass) {
                        Toast.makeText(HandWriteAllClassAnswerActivity.this, "请先连接教师端", Toast.LENGTH_LONG).show();
                    } else {

                        sendFile(v);

                    }
                    break;
            }

        }
    }

    /**
     * 提交图片
     */
    private void sendFile(View view) {
        if (hasCommit){
            ToastUtils.makeText(HandWriteAllClassAnswerActivity.this,"答案已经提交");
            return;
        }
        hasCommit=true;


        mTool_ll.setVisibility(View.GONE);
        mCommit_img.setVisibility(View.GONE);
      //  mName.setVisibility(View.VISIBLE);
       // mName.setText(BaseApplication.sUserBean.getPersonalbean().getRealName() + "");
        mTempBitmap = screenShot();
        if (mTempBitmap !=null){

            if (mUpLoadPopu != null) {
                if (mUpLoadPopu.isShowing()) {
                    mUpLoadPopu.dismiss();
                }
            } else {
                mUpLoadPopu = new UpLoadPopuWindow(HandWriteAllClassAnswerActivity.this);
            }
            mUpLoadPopu.showAtLocation(view, Gravity.CENTER, 0, 0);

            mName.setVisibility(View.GONE);
            mTool_ll.setVisibility(View.VISIBLE);
            mCommit_img.setVisibility(View.VISIBLE);

            mFilePath = FileUtils.IMAGE_DIR + BaseApplication.sUserBean.getUserbean().getId() + UIUtils.getUUidString() + ".jpg";
            File file = new File(mFilePath);

            try {
                if (!file.exists()) {
                    file.createNewFile();
                }

                mTempBitmap = ImageUtils.zoomBitmap(mTempBitmap,
                        (int) (mDeviceWidth * CommonConfig.ReciveImgZoomProportion),
                        (int) (mDeviceHeight * CommonConfig.ReciveImgZoomProportion));
                mTempBitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file));
                uploadPic(file);
                if (mTempBitmap != null && !mTempBitmap.isRecycled()) {
                    mTempBitmap.recycle();
                    mTempBitmap =null;
                }
            } catch (IOException e) {
                e.printStackTrace();
                hasCommit=false;
                ToastUtils.makeText(this,"图片上传失败");
            }


        }else {
            //截屏失败
            hasCommit=false;
            mName.setVisibility(View.GONE);
            mTool_ll.setVisibility(View.VISIBLE);
            mCommit_img.setVisibility(View.VISIBLE);

        }
    }

    /**
     * 上传图片
     * @param file
     */
    private void uploadPic(final File file) {

        mFtpDir = "/classroom/"+ BaseApplication.sUserBean.getSchoolId()+"/student/"
                +BaseApplication.sUserBean.getPersonalbean().getId()
                +"/hwhiteboard/area/";
      ThreadFactory.getDownLoadPool().submit(new Runnable() {
          @Override
          public void run() {
              FtpUtils ftpUtils=new FtpUtils();
              try {
                  ftpUtils.uploadSingleFile(file, mFtpDir,mImageName, new FtpUtils.UploadProgressListener() {
                      @Override
                      public void onUploadProgress(String currentStep, long uploadSize, File file) {

                          switch (currentStep) {
                              case Config.FTP_UPLOAD_SUCCESS :
                                  Message message = mHandler.obtainMessage();
                                  message.what=FTP_UPLOAD_SUCCESS;
                                  mHandler.sendMessage(message);
                                  //发送上传成功图片
                                 logcatI("图片上传 路径 ： "+ mFtpDir +file.getName());
                                  break;
                              case Config.FTP_UPLOAD_LOADING :
                                 int prient= (int) ((uploadSize*100/file.length()));
                                  Message message1 = mHandler.obtainMessage();
                                  message1.what=FTP_UPLOAD_LOADING;
                                  message1.obj=prient;
                                  mHandler.sendMessage(message1);
                                  break;
                              case Config.FTP_CONNECT_FAIL:
                              case Config.FTP_UPLOAD_FAIL :
                                  Message message2 = mHandler.obtainMessage();
                                  message2.what=FTP_UPLOAD_FAIL;
                                  mHandler.sendMessage(message2);
                                  break;


                          }

                      }
                  });
              } catch (Exception e) {
                  Message message2 = mHandler.obtainMessage();
                  message2.what=FTP_UPLOAD_FAIL;
                  mHandler.sendMessage(message2);
                  e.printStackTrace();
                  ToastUtils.makeText(HandWriteAllClassAnswerActivity.this,"上传文件失败");
              }


          }
      });
        //保存到本地数据库

    }



    /**
     * 截取当前屏幕
     * @return
     */
    private Bitmap screenShot() {
        View view = getWindow().getDecorView();
        if (view == null) {
            return null;
        }
        view.layout(0, 0, mDeviceWidth, mDeviceHeight);
        view.setDrawingCacheEnabled(true);
        Bitmap bmp = null;
        try {
            bmp = view.getDrawingCache();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return bmp;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mReceiver!=null){
            unregisterReceiver(mReceiver);
            mReceiver=null;
        }
        if (mBitmap!=null && !mBitmap.isRecycled()){
            mBitmap.recycle();
            mBitmap=null;
            System.gc();
        }
        if (mTempBitmap != null && !mTempBitmap.isRecycled()) {
            mTempBitmap.recycle();
            mTempBitmap=null;
        }

        if (mUpLoadPopu!=null && mUpLoadPopu.isShowing()){
            mUpLoadPopu.dismiss();
        }
        if (mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
        }

    }
}
